package com.cytech.cloudclinic.http.interceptor;

import com.cytech.cloudclinic.utils.NetLogHelper;
import com.cytech.cloudclinic.utils.OKHttpBodyParseHelper;

import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class NetLogInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        RequestBody requestBody = request.body();
        boolean hasRequestBody = requestBody != null;
        if(hasRequestBody){
            String requestBodyStr = OKHttpBodyParseHelper.getReqBodyString(request);
            NetLogHelper.getInstance().putRequest(request.url().toString(),request.method(),requestBodyStr);
        }

        Response response = chain.proceed(request);
        Response.Builder builder = response.newBuilder();
        Response clone = builder.build();
        ResponseBody responseBody = clone.body();
        NetLogHelper.getInstance().putResponse(request.method(),responseBody.bytes().toString());

        return response;
    }
}
